#!/usr/bin/env node

var inquirer = require('inquirer');
var shell = require('shelljs');
var mergeRequest = require('./mergeRequest').mergeRequest;

if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git');
  shell.exit(1);
}

var exec = require('child_process').exec;

var branchList = {
  type: 'list',
  name: 'branch',
  message: '推送这个分支？',
  choices: []
};

function __main__() {
  exec('git branch', function (err, stdout) {
    // 获取当前分支的名字
    var targetBranchTemp = '';
    var branchArray = stdout.split('\n');
    branchArray.every(item => {
      item = item.replace(/\s+/g, '');
      if (item.indexOf('*') >= 0) {
        targetBranchTemp = item;
        return false;
      }
      return true;
    });
    if (targetBranchTemp.length > 0) {
      branchList.choices = [targetBranchTemp];
    }

    inquirer
      .prompt([branchList])
      .then(answers => answers.branch)
      .then(branch => {
        exec('git push -u origin HEAD', function (err) {
          if (!err) {
            console.log(`------${new Date().toLocaleString()}------`);
            console.log('------Push成功------');
            var currentBranchName = branch.replace(/\*/, '');
            exec('git log -1 --pretty=%B', function (error, stdout) {
              mergeRequest(currentBranchName, stdout);
            });
          }
        });
      });
  });
}

__main__();